package com.mck.service.impl;

import com.mck.entity.Classname;
import com.mck.entity.UserClassname;
import com.mck.entity.User;
import com.mck.mapper.ClassnameMapper;
import com.mck.mapper.UserClassnameMapper;
import com.mck.mapper.UserMapper;
import com.mck.service.UserClassnameService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserClassnameServiceImpl implements UserClassnameService {

    @Autowired
    private UserClassnameMapper userClassnameMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ClassnameMapper classnameMapper;

    // 获取用户班级关系列表
    @Override
    @Cacheable(value = "userClassnameList", key = "'all'", unless = "#result.isEmpty()")
    public List<UserClassname> getUserClassnameList() {
        return userClassnameMapper.getUserClassnameList();
    }

    // 根据班级id获取用户列表
    @Override
    @Cacheable(value = "userListByClassId", key = "#userTypeId + '_' + #classIdList", unless = "#result.isEmpty()")
    public List<User> getUserListByClassId(Integer userTypeId, List<Integer> classIdList) {
        // 创建一个新的user列表
        List<User> userList = new ArrayList<>();

        for (Integer classId : classIdList) {
            // 获取班级对应的用户关联信息
            List<UserClassname> userClassnames = userClassnameMapper.getUserListByClassId(classId, userTypeId);

            // 遍历 UserClassname 列表，提取 userId
            for (UserClassname userClassname : userClassnames) {
                Integer userId = userClassname.getUserId(); // 获取userId

                // 构建user对象（因为findUserInfoByUserInfo（）需要user对象）
                User newUser = new User();
                newUser.setUserId(userId);

                // 根据 userId 查询用户信息
                List<User> user = userMapper.findUserInfoByUserInfo(newUser);
                if (user != null && !user.isEmpty()) {
                    userList.addAll(user); // 将查询到的用户信息添加到结果列表
                }
            }
        }

        return userList;
    }

    // 根据用户id获取班级列表
    @Override
    @Cacheable(value = "classnameListByUserId", key = "#userId", unless = "#result.isEmpty()")
    public List<Classname> getClassnameListByUserId(Integer userId) {
        List<UserClassname> userClassnameList = userClassnameMapper.getClassnameListByUserId(userId);

        // 创建一个新的班级列表
        List<Classname> classnameList = new ArrayList<>();
        for (UserClassname userClassname : userClassnameList) {
            Integer classId = userClassname.getClassId();

            Classname classname = classnameMapper.getClassnameById(classId);
            classnameList.add(classname);
        }

        return classnameList;
    }
}
